<template>
  <!-- 新结算日账单 -->
  <div class="home-page-container">
    <!-- search 查询 -->
    <el-card shadow="never">
      <mer-search :searchConfig="formConfig" :searchBar="searchBar"
        @search="search"
        @reset="reset"
        @changeTime="(value,model)=>changeTime(value,'searchBar', 'tradeTimeStart', 'tradeTimeEnd')"
        :loading="tableLoading">
        <template slot="collectionOrder" v-if="showPos">
          <el-select v-model="searchBar.businessSource" :clearable="false" @change="changeOrder">
            <el-option v-for="(item,key) in collectionOrderOptions" :key="key" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </template>
        <template slot="yeepay" v-if="showPos && searchBar.businessSource == 1">
          <el-select v-model="searchBar.receiveBusiness" :clearable="false">
            <el-option v-for="item in yeeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </template>
        <template slot="handler">
          <el-button size="mini" @click="download" icon="el-icon-download">导出</el-button>
          <el-button size="mini" @click="gotoOldBill">8月4日前日账单 >>></el-button>
        </template>
      </mer-search>
    </el-card>
    <dayBillPosTab :showPos="showPos" @handleChangeType="handleChangeType" :isActiveType="isActiveType" :sumInfoAll="sumInfoAll" :sumTuanInfoData="sumTuanInfoData" :posSumInfoData="posSumInfoData"></dayBillPosTab>
    <el-card class="order-card" shadow="never" :body-style="{ padding: '0'}" style="margin-top: 20px;border: none">
      <el-table v-loading="loading" size="small" :data="tableData"  highlight-current-row border  style="width: 100%">
        <el-table-column v-for="(item, index) in isPosTable ? posConfig : tableConfig" :key="index" :prop="item.prop" :width="item.width" :label="item.label" :align="item.align"></el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.pageIndex"
        :page-sizes="pageSizes"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="tablePagination">
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
import listPage from '@/mixins/listPage'
import queryMix from '@/views/finance/mixins/query';
import dayBillPosTab from './components/bill/dayBillPosTab'
import { getDailyQueryStatusApi, getDailyBillSummaryApi, getDailyBillListApi, downloadDailyBillApi, getHasPosRightInHistory, receiveBusinessList } from '@/api/finance'

  // 查询表单配置
let formConfig = [
  { label: '油站', type: 'select', modelName: 'gasId', placeholder: '全部', selectOptions: [], define: true, selectLabel: 'gasName', selectValue: 'gasId' },
  { label: '账单日期', type: 'date', modelName: 'tradeTime', model: '', dateType: 'daterange', format: 'yyyy-MM-dd HH:mm:ss',pickerOptions:{}, clearable:false},
  { label: '账单状态', type: 'select', modelName: 'billStatus', placeholder: '全部', selectOptions: [], define: true, selectLabel: 'label', selectValue: 'value' },
  { label: '收单方式', type:'slot', slotName: 'collectionOrder'},
  { label: '结算方', type:'slot', slotName: 'yeepay'}
]
// 表格参数配置
let tableConfig = [
  { label: '账单日期', prop: 'settlementDate', slot:'settlementDate', width: 150 },
  { label: '油站名称', prop: 'gasName', width: 136  },
  { label: '加油金额(元)', prop: 'amountGun', width: 136 },
  { label: '让利金额(元)', prop: 'amountRebate', width: 136},
  { label: '应结算金额(元)', prop: 'billAmount', width: 136 },
  { label: '通道费金额(元)', prop: 'slottingFee', width: 136 },
  { label: '商家承担直降金额', prop: 'amountActivityMerchant', width: 136 },
  { label: '商家承担平台优惠券金额', prop: 'amountPlatformCouponMerchant', width: 156 },
  { label: '商家优惠券', prop: 'merchantCouponAmount', width: 136},
  { label: '实际结算金额(元)', prop: 'realSettlementAmount', width: 136 },
  { label: '消费升数', prop: 'litre' },
  { label: '交易笔数', prop: 'tradeCount' },
  { label: '通道费周期', prop: 'settlementCycleName',width: 136 },
  { label: '账单状态', prop: 'billStatusName',width: 136 },
  { label: '账单生成时间', prop: 'createTime',width: 150 }
]

// pos参数配置
let posConfig = [
  { label: '账单日期', prop: 'settlementDate', slot:'settlementDate', width: 150 },
  { label: '油站名称', prop: 'gasName', width: 136  },
  { label: '加油金额(POS收单)', prop: 'amountGun', width: 136 },
  { label: '应结算金额(POS收单)', prop: 'billAmount', width: 136 },
  { label: '通道费金额(POS收单)', prop: 'slottingFee', width: 136 },
  { label: '实际结算金额(POS收单)', prop: 'realSettlementAmount', width: 136 },
  { label: '结算方', prop: 'receiveBusinessName', width: 136 },
  { label: '消费升数(POS收单)', prop: 'litre' },
  { label: '交易笔数(POS收单)', prop: 'tradeCount' },
  { label: '通道费周期', prop: 'settlementCycleName',width: 136 },
  { label: '账单状态', prop: 'billStatusName',width: 136 },
  { label: '账单生成时间', prop: 'createTime',width: 150 }
]

export default {
  name: 'bill_dailyBill',
  mixins:[ listPage, queryMix ],
  components: { dayBillPosTab },
  data(){
    return{
      isPosTable: false,
      showPos: false,
      tradeTime:'',
      formConfig: formConfig,
      tableConfig: tableConfig, // 团油表格
      posConfig: posConfig, // pos 表格
      tableData: [],
      isActiveType: 0, // tab切换
      sumInfoAll: {}, // 总汇总信息
      sumTuanInfoData: {}, // 团油收单会综合
      posSumInfoData: {}, // pos收单汇总
      loading: false,
      pagination: {
        pageIndex: 1,
        pageSize: 20
      },
      total: 0,
      pageSizes: [20],
      searchBar: { businessSource: 0, receiveBusiness: null },
      collectionOrderOptions: [{ label: '团油收单', value: 0 }, { label: 'POS收单', value: 1 }],
      yeeOptions: []
    }
  },
   created(){
    this.initPage()
    this.getHasPosRightInHistoryApi()
  },
  methods:{
    initPage () {
      this.initQuery()
      this.getQueryStatus()
      this.getAllGasStations()
      // this.receiveBusinessListApi()
      this.refresh()
    },  
    // 重置，设置默认查询条件，默认时间间隔7天
    initQuery () {
      this.tradeTime = ''
      this.initTime('tradeTime', 6, 'searchBar',true, 'tradeTimeStart', 'tradeTimeEnd')
      const { tradeTime, pickerOptions } = this
      const initObj = { tradeTime: [tradeTime, pickerOptions] }
      this.setSearchConfig(initObj)
      this.formConfig.splice(4, 1) // 删除
      // this.searchBar.receiveBusiness = null // 团油不传结算方式参数
    },
    // 切换收单方式, 结算方查询条件是否展示
    changeOrder (val) {
      this.isActiveType = val
      const yeepay = { label: '结算方', type:'slot', slotName: 'yeepay'}
      if (val === 1) {
        this.formConfig.push(yeepay)
        this.searchBar.receiveBusiness = '2'
      } else {
        this.formConfig.pop()
        this.searchBar.receiveBusiness = null
      }
      this.refresh()
    },
    // 字传父切换
    handleChangeType (val) {
      this.isActiveType = val
    },
     // 获取查询条件：账单状态
    async getQueryStatus(){
      const data = { companyId:'', gasId:'', account:''}
      try{
        const { code, result = [] } = await getDailyQueryStatusApi(data)
        if(code !== 200) return
        const initObj = { billStatus: this.optionsWrapper(result) }
        this.setSearchConfig(initObj)
      }catch(err){
        console.log(err)
      }
    },
    // 每页多少天改变时
    handleSizeChange (val) {
      console.log(val)
    },
    // 切换分页
    handleCurrentChange (val) { // 翻页
      this.pagination.pageIndex = val
      this.refresh()
    },
    //导出
    download () {
      this.downloadFile(downloadDailyBillApi,'结算日账单')
    },
    gotoOldBill(){
      this.$router.push({path:'/bill/oldDailyBill'})
    },
    // 查询条件重置
    reset (initQuery, searchName = 'searchBar') {
      this.isActiveType = 0
      this.$data[searchName] = { receiveBusiness: undefined }
      this.searchBar.businessSource = this.showPos ? 0 : null // 重置，收单方式默认团油收单
      this.initQuery()
      this.search()
    },
    // 判断是否存在pos
    async getHasPosRightInHistoryApi() {
      try {
        const { code, result } = await getHasPosRightInHistory()
        if(code !== 200) return
        this.showPos = result
        if (result) {
          this.receiveBusinessListApi()
        } else {
          this.formConfig.splice(3, 1)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 获取table ||  特殊的请求或数据处理，可以覆写该方法
    async refresh () {
      this.tableLoading = true
      const data = { ...this.searchBar, ...this.pagination }
      //对查询条件做一次缓存
      this.downloadParams = { ...this.searchBar }
      this.getSumInfo(data)
      try{
        this.isPosTable = data.businessSource !== 0
        const { code, result = [], totalRow = 0 } = await getDailyBillListApi(data)
        if(code !== 200) return
        this.tableData = result
        this.total = parseInt(totalRow)
      }catch(err){
        console.log(err)
      }finally{
        this.tableLoading = false
      }
    },
    // 列表汇总（统计）信息
    async getSumInfo (data) {
      try{
        const { code, result } = await getDailyBillSummaryApi(data)
        if(code !== 200) return
        const { posDailyBillSummary, appDailyBillSummary } = result
        this.sumInfoAll = result || {}
        this.sumTuanInfoData = appDailyBillSummary || {} // 团油收单汇总
        this.posSumInfoData = posDailyBillSummary || {} // pos收单汇总
      }catch(err){
        console.log(err)
      }
    },
    // 结算方式枚举
    async receiveBusinessListApi () {
      try {
        let { code, result: { receiveBusiness } } = await receiveBusinessList()
        if(code !== 200) return
        this.yeeOptions = Object.entries(receiveBusiness).map(itemArr => ({ value: itemArr[0], label: itemArr[1] }))
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
<style lang="less" scoped>
.home-page-container{
  margin-top: 20px;
}
.tablePagination{
  margin: 15px 0;
  float: right;
}
</style>